﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using System.IO;
using Microsoft.VisualStudio;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using System.Xml;

namespace PovTeam.Pkg_PovrayProject
{

    [Guid(GuidList.guidPkg_PovrayProjectFactoryString)]
    class PovrayProjectFactory : IVsProjectFactory
    {

        private Pkg_PovrayProjectPackage package;
        private IOleServiceProvider site;

        public PovrayProjectFactory(Pkg_PovrayProjectPackage package)
        {
            this.package = package;
            site = package;
        }
        
        #region IVsProjectFactory Members

        public Pkg_PovrayProjectPackage Package
        {
            get { return package; }
        }

        public int CanCreateProject(string pszFilename, uint grfCreateFlags, out int pfCanCreate)
        {
            if (!File.Exists(pszFilename) || 0 != (grfCreateFlags & (uint)(__VSCREATEPROJFLAGS.CPF_OVERWRITE | __VSCREATEPROJFLAGS.CPF_CLONEFILE) ))
            {
                pfCanCreate = 1;
            }
            else
            {
                pfCanCreate = 0;
            }

            return VSConstants.S_OK;
        }

        public int Close()
        {
            return VSConstants.S_OK;
        }

        

        public int CreateProject(string pszFilename, string pszLocation, string pszName, uint grfCreateFlags, ref Guid iidProject, out IntPtr ppvProject, out int pfCanceled)
        {
            if (!File.Exists(pszFilename) || 0 != (grfCreateFlags & (uint)(__VSCREATEPROJFLAGS.CPF_OVERWRITE | __VSCREATEPROJFLAGS.CPF_CLONEFILE)))
            {
                PovrayProjectNode project = new PovrayProjectNode(this);
                project.Load(pszFilename, 1, 0);
                project.Filename = Path.Combine(pszLocation, pszName);

                pfCanceled = 0;
                ppvProject = Marshal.GetIUnknownForObject(project);
                return VSConstants.S_OK;
            }
            else
            {
                ppvProject = IntPtr.Zero;
                pfCanceled = 1;
                return VSConstants.E_FAIL;
            }
        }

        public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp)
        {
            site = psp;
            return VSConstants.S_OK;
        }

        #endregion

        internal IOleServiceProvider GetOleServiceProvider()
        {
            return (IOleServiceProvider)this.package;
        }
    }
}
